<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="75px">
        <el-form-item label="物料编号">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入物料编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input
            v-model="searchParam.materialName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="存储批次">
          <el-input
            v-model="searchParam.stockBatch"
            placeholder="请输入存储批次"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select
            v-model="searchParam.warehouseId"
            clearable
            placeholder="请选择仓库"
            @change="warehouseChange"
          >
            <el-option
              v-for="item in warehouses"
              :key="item.id"
              :label="item.warehouseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="存储区">
          <el-select
            v-model="searchParam.storageSectionId"
            clearable
            placeholder="请选择存储区"
            @change="storageSectionChange"
          >
            <el-option
              v-for="item in storageSections"
              :key="item.id"
              :label="item.storageSectionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="料架">
          <el-select
            v-model="searchParam.shelfId"
            clearable
            placeholder="请选择料架"
            @change="shelfChange"
          >
            <el-option
              v-for="item in shelfs"
              :key="item.id"
              :label="item.shelfName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓位">
          <el-select
            v-model="searchParam.binId"
            clearable
            placeholder="请选择仓位"
          >
            <el-option
              v-for="item in bins"
              :key="item.id"
              :label="item.binName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="包装编号">
          <el-input
            v-model="searchParam.storageCode"
            placeholder="请输入包装编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="rfid号">
          <el-input
            v-model="searchParam.rfid"
            placeholder="请输入rfid号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table ref="dataTableRef" v-loading="loading" :data="tableData" border>
        <el-table-column
          label="物料编号"
          prop="materialCode"
          min-width="80"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="物料名称"
          prop="materialName"
          min-width="120"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="存储批次"
          prop="stockBatch"
          min-width="80"
          show-overflow-tooltip
        >
        </el-table-column>
        <!-- <el-table-column
          label="供应批次"
          prop="supplyBatch"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="供应商名称"
          prop="supplierName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>-->
        <el-table-column
          label="仓库名称"
          prop="warehouseName"
          min-width="90"
          show-overflow-tooltip
        >
        </el-table-column>
        <!-- <el-table-column
          label="存储区名"
          prop="storageSectionName"
          min-width="90"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="料架名称"
          prop="shelfName"
          min-width="90"
          show-overflow-tooltip
        >
        </el-table-column> -->
        <el-table-column
          label="仓位名"
          prop="binName"
          min-width="90"
          show-overflow-tooltip
        >
        </el-table-column>
        <!-- <el-table-column
          label="总数量"
          prop="totalQuantity"
          min-width="65"
          show-overflow-tooltip
        >
        </el-table-column> -->
        <el-table-column
          label="可用数量"
          prop="availableQuantity"
          min-width="75"
          show-overflow-tooltip
        >
        </el-table-column>
        <!-- <el-table-column
          label="限制使用数量"
          prop="freezeQuantity"
          min-width="110"
          show-overflow-tooltip
        >
        </el-table-column> -->
        <el-table-column
          label="盘点封存数量"
          prop="transferQuantity"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="数量单位"
          prop="quantityUnit"
          min-width="75"
          show-overflow-tooltip
        >
        </el-table-column>
        <!-- <el-table-column
          label="rfid号"
          prop="rfid"
          min-width="75"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="是否寄存"
          prop="isDeposit"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-tag>
              {{ dictionaryStore.filterDictName("YesNo", scope.row.isDeposit) }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column
          label="外部编号"
          prop="storageCode"
          min-width="300"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            {{ formatName(row.storageCode) }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="poSaSd"
          prop="remarks"
          min-width="200"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="临期状态"
          prop="stockageType"
          min-width="300"
          show-overflow-tooltip
        >
        </el-table-column> -->
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />调整</el-button
            >
            <!-- v-if="authAllPerm(['npm:wmspart:update'])" -->
            <el-button
              type="primary"
              size="small"
              link
              @click="openLabel(scope.row.storageCode)"
              >打印标签</el-button
            >
            <!-- v-if="authAllPerm(['npm:wmspart:print'])" -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <wmspart-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <label-printing-code
      :visible="labelDialog2.visible"
      :title="labelDialog2.title"
      :data="labelDialog2.data"
      :is-readonly="labelDialog2.readvisible"
      @change-visible="labelVisible2"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { authAllPerm } from "@/utils/index";

import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "WMSWMSPART",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/wms/wmspart/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  partCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  stockBatch: "",
  supplyBatch: "",
  supplierId: "",
  supplierCode: "",
  supplierName: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  warehouseId: "",
  warehouseCode: "",
  warehouseName: "",
  storageTypeId: "",
  storageTypeCode: "",
  storageTypeName: "",
  storageSectionId: "",
  storageSectionCode: "",
  binId: "",
  binCode: "",
  storageUnitId: "",
  extenalCode: "",
  goodsReceiptTimeSearch: [],
  goodsReceiptTimeStart: "",
  goodsReceiptTimeEnd: "",
  materialDocumentId: "",
  materialDocumentCode: "",
  materialDocumentDetailId: "",
  materialDocumentDetailCode: "",
  totalQuantity: "",
  availableQuantity: "",
  freezeQuantity: "",
  transferQuantity: "",
  quantityUnit: "",
  usedColume: "",
  usedArea: "",
  usedWeight: "",
  isCheck: "",
  chemicalCompositionId: "",
  createTimeSearch: [],
  createTimeStart: "",
  createTimeEnd: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTimeSearch: [],
  lastUpdateTimeStart: "",
  lastUpdateTimeEnd: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  storageSectionName: "",
  shelfId: "",
  shelfCode: "",
  shelfName: "",
  binName: "",
  storageCode: "",
  rfid: "",
};

const labelDialog2 = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

/** 打开入库申请表单弹窗 详情 */
function openLabel(roleObj?: any) {
  labelDialog2.title = "打印标签";
  console.log("打印标签");
  labelDialog2.data = roleObj;
  labelDialog2.readvisible = true;
  labelDialog2.visible = true;
}

function labelVisible2(value: boolean) {
  labelDialog2.visible = value;
}

const addDialog2 = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

const deleteParam = {
  api: "/wms/wmspart/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/wms/wmspart/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开份库存表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改库存信息";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增份库存";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开份库存表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "份库存详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getgoodsReceiptTime(data: any) {
  if (data) {
    searchParam.value.goodsReceiptTimeStart = data[0];
    searchParam.value.goodsReceiptTimeEnd = data[1];
  } else {
    searchParam.value.goodsReceiptTimeStart = "";
    searchParam.value.goodsReceiptTimeEnd = "";
  }
}
function getcreateTime(data: any) {
  if (data) {
    searchParam.value.createTimeStart = data[0];
    searchParam.value.createTimeEnd = data[1];
  } else {
    searchParam.value.createTimeStart = "";
    searchParam.value.createTimeEnd = "";
  }
}
function getlastUpdateTime(data: any) {
  if (data) {
    searchParam.value.lastUpdateTimeStart = data[0];
    searchParam.value.lastUpdateTimeEnd = data[1];
  } else {
    searchParam.value.lastUpdateTimeStart = "";
    searchParam.value.lastUpdateTimeEnd = "";
  }
}

// 导入excel
const uploadApi = "/wms/wmspart/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/wms/wmspart/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
onMounted(() => {
  getPartner();
  //getInboundType();
  getWarehouses();
});
let partners = ref([]);
async function getPartner() {
  const data = await request({
    url: "/wms/mdmpartner/getList",
    method: "get",
  });
  partners.value = data.data;
}
// let inboundTypes = ref([]);
// async function getInboundType() {
//   const data = await request({
//     url: "/wms/wmsinboundtype/getList",
//     method: "get",
//   });
//   inboundTypes.value = data.data;
// }
let warehouses = ref([]);
async function getWarehouses() {
  const data = await request({
    url: "/wms/wmswarehouse/getList",
    method: "get",
  });
  warehouses.value = data.data;
}
function warehouseChange(id: string) {
  searchParam.value.storageSectionId = "";
  searchParam.value.shelfId = "";
  if (id) {
    console.log("warehouseChange");
    storageSections.value = [];
    getStorageSections();
    bins.value = [];
    getDins();
  }
}
let storageSections = ref([]);
async function getStorageSections() {
  const data = await request({
    url: "/wms/wmsstoragesection/getList/" + searchParam.value.warehouseId,
    method: "get",
  });
  storageSections.value = data.data;
}
function storageSectionChange(id: string) {
  searchParam.value.shelfId = "";
  shelfs.value = [];
  if (id) {
    getShelf();
  }
}
let shelfs = ref([]);
async function getShelf() {
  shelfs.value = [];
  const data = await request({
    url: "/wms/wmsshelf/getList/" + searchParam.value.storageSectionId,
    method: "get",
  });
  shelfs.value = data.data;
}
function shelfChange(id: string) {
  if (id) {
    var shelf = shelfs.value.find((item) => {
      return item.id === searchParam.value.shelfId;
    });
    searchParam.value.shelfCode = shelf.shelfCode;
    searchParam.value.shelfName = shelf.shelfName;
    bins.value = [];
    getDins();
  }
}
let bins = ref([]);
async function getDins() {
  const data = await request({
    url: "/wms/wmsbin/getOptionList",
    method: "post",
    data: {
      shelfId: searchParam.value.shelfId,
      storageSectionId: searchParam.value.storageSectionId,
      warehouseId: searchParam.value.warehouseId,
    },
  });
  bins.value = data.data;
}
function binChange(id: string) {
  if (id) {
    var bin = bins.value.find((item) => {
      return item.id === searchParam.value.binId;
    });
    searchParam.value.binCode = bin.binCode;
    searchParam.value.binName = bin.binName;
  }
}

const cellStyle = (data) => {
  console.log(data.row.stockageType);
  if (data.row.stockageType === "NOK") {
    return {
      color: "#000",
      background: "#FF4500",
      fontWeight: 700,
    };
  }
  if (data.row.stockageType === "Alert") {
    return {
      color: "#000",
      background: "#FFDEAD",
      fontWeight: 700,
    };
  }
};
function formatName(outCode: string) {
  return outCode.split("Q")[0];
}
</script>
